<template>
  <div v-if="hasDataScope" class="data-scope-guard">
    <slot />
  </div>
  <div v-else-if="showDenied" class="data-scope-denied">
    <el-empty 
      :image-size="120"
      description="数据权限不足"
    >
      <template #description>
        <div class="data-scope-denied-content">
          <el-icon class="data-scope-icon" size="48" color="#f56c6c">
            <Lock />
          </el-icon>
          <h3 class="data-scope-title">数据权限不足</h3>
          <p class="data-scope-message">
            {{ message || '非物业公司人员不能查看本页面数据，请联系管理员获取相应权限。' }}
          </p>
          <div class="data-scope-info" v-if="dataScopeInfo">
            <el-alert
              :title="dataScopeInfo.scopeDescription"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
          <div class="data-scope-actions">
            <el-button type="primary" @click="contactAdmin">
              <el-icon><Message /></el-icon>
              联系管理员
            </el-button>
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              返回上一页
            </el-button>
            <el-button @click="goHome">
              <el-icon><House /></el-icon>
              返回首页
            </el-button>
          </div>
        </div>
      </template>
    </el-empty>
  </div>
  <div v-else class="data-scope-guard">
    <!-- 不显示任何内容，静默处理 -->
  </div>
</template>

<script setup lang="ts">
/**
 * 数据权限守卫组件
 * @author Wu.Liang
 * @date 2025-07-01
 * @description 专门用于检查用户物业公司数据权限的组件
 */
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { Lock, ArrowLeft, House, Message } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { showSuccess, showError, showWarning, showInfo } from '@/utils/message'
import { 
  isSuperAdmin, 
  getUserDataScope 
} from '@/utils/permission'

interface Props {
  /** 是否显示权限不足提示 */
  showDenied?: boolean
  /** 权限不足时的提示信息 */
  message?: string
  /** 是否需要物业公司权限 */
  requirePropertyCompany?: boolean
  /** 所需社区权限 */
  requiredCommunityIds?: number[]
  /** 是否自动刷新权限 */
  autoRefresh?: boolean
  /** 模块名称，用于选择对应的API */
  module?: 'property' | 'parking' | 'region' | 'user'
}

interface DataScopeInfo {
  userId: number
  dataScopeType: number
  communityIds: number[]
  propertyCompanyIds: number[]
  restrictions: string
  isSuperAdmin: boolean
  scopeDescription: string
}

const props = withDefaults(defineProps<Props>(), {
  showDenied: true,
  requirePropertyCompany: true,
  autoRefresh: false,
  module: 'property'
})

const router = useRouter()
const userStore = useUserStore()

const dataScopeInfo = ref<DataScopeInfo | null>(null)
const loading = ref(false)

/**
 * 根据模块获取对应的数据权限API
 */
const getDataScopeApi = () => {
  switch (props.module) {
    case 'parking':
      return import('@/api/parking').then(module => module.dataScopeApi)
    case 'region':
      return import('@/api/region').then(module => module.dataScopeApi)
    case 'user':
      return import('@/api/user').then(module => module.dataScopeApi)
    case 'property':
    default:
      return import('@/api/property').then(module => module.dataScopeApi)
  }
}

/**
 * 检查是否有数据权限
 */
const hasDataScope = computed(() => {
  // 超级管理员拥有所有权限
  if (isSuperAdmin()) {
    console.log('DataScopeGuard: 超级管理员权限检查通过')
    return true
  }

  // 检查社区权限
  if (props.requiredCommunityIds?.length) {
    const userDataScope = getUserDataScope()
    const hasCommunityPermission = props.requiredCommunityIds.some(communityId =>
      userDataScope.includes(communityId.toString())
    )
    if (!hasCommunityPermission) {
      console.log('DataScopeGuard: 用户社区权限不足')
      return false
    }
  }

  return true
})

/**
 * 获取数据权限信息
 */
const fetchDataScopeInfo = async () => {
  try {
    loading.value = true
    const dataScopeApi = await getDataScopeApi()
    const response = await dataScopeApi.getDataScopeInfo()
    if (response.code === 200) {
      dataScopeInfo.value = response.data
    }
  } catch (error) {
    console.error('获取数据权限信息失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 联系管理员
 */
const contactAdmin = () => {
  showInfo('请联系系统管理员获取物业公司权限')
  // 这里可以打开联系管理员的对话框或跳转到联系页面
}

/**
 * 返回上一页
 */
const goBack = () => {
  if (window.history.length > 1) {
    router.back()
  } else {
    router.push('/dashboard')
  }
}

/**
 * 返回首页
 */
const goHome = () => {
  router.push('/dashboard')
}

/**
 * 刷新权限
 */
const refreshPermission = () => {
  if (props.autoRefresh) {
    fetchDataScopeInfo()
  }
}

// 组件挂载时获取权限信息
onMounted(() => {
  if (props.showDenied) {
    fetchDataScopeInfo()
  }
})

// 暴露方法供父组件调用
defineExpose({
  refreshPermission,
  hasDataScope: hasDataScope.value
})
</script>

<style lang="scss" scoped>
.data-scope-guard {
  width: 100%;
  height: 100%;
}

.data-scope-denied {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px 20px;
  
  .data-scope-denied-content {
    text-align: center;
    max-width: 500px;
    
    .data-scope-icon {
      margin-bottom: 16px;
      opacity: 0.8;
    }
    
    .data-scope-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 12px 0;
    }
    
    .data-scope-message {
      font-size: 14px;
      color: #606266;
      margin: 0 0 20px 0;
      line-height: 1.6;
    }
    
    .data-scope-info {
      margin: 0 0 24px 0;
      
      .el-alert {
        text-align: left;
      }
    }
    
    .data-scope-actions {
      display: flex;
      gap: 12px;
      justify-content: center;
      flex-wrap: wrap;
      
      .el-button {
        min-width: 120px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .data-scope-denied {
    padding: 20px 16px;
    
    .data-scope-denied-content {
      .data-scope-title {
        font-size: 20px;
      }
      
      .data-scope-message {
        font-size: 13px;
      }
      
      .data-scope-actions {
        flex-direction: column;
        align-items: center;
        
        .el-button {
          width: 100%;
          max-width: 200px;
        }
      }
    }
  }
}
</style> 